/*
#**************************************************************************
#  openSIS is a student information system for public and non-public 
#  schools from Open Solutions for Education, Inc. web: www.os4ed.com
#
#  openSIS is  web-based, open source, and comes packed with features that 
#  include student demographic info, scheduling, grade book, attendance, 
#  report cards, eligibility, transcripts, parent portal, 
#  student portal and more.   
#
#  Visit the openSIS web site at http://www.opensis.com to learn more.
#  If you have question regarding this system or the license, please send 
#  an email to info@os4ed.com.
#
#  This program is released under the terms of the GNU General Public License  
#  as  published by the Free Software Foundation, version 2 of the License. 
#  See license.txt.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#**************************************************************************** 
*/
 
using System;
using System.Data;
using System.Collections;
using System.Web.UI;
using calendar.Configuration;
using calendar.Data;
using System.Text.RegularExpressions;
 
namespace calendar
{
 
	public class CommonFunctions
	{
		//ASP 3.0 / PHP pattern commons

		//---------------------------------------
		//Add the parameter with specified value into the GET query string
		//---------------------------------------
		public static string CCAddParam(string QueryString, string ParameterName, string ParameterValue)
		{
			string result = QueryString.TrimEnd(new Char[]{'?'});
			int i = result.ToLower().IndexOf(ParameterName.ToLower() + "=");
			int j = 0;
			if (i > 1) i = result.ToLower().IndexOf("&" + ParameterName.ToLower() + "=");
			if (i > 0) j = result.ToLower().IndexOf("&", i + 1);

			while (i > 0) 
			{
				if (j > 0) result = result.Substring(0, i - 1) + result.Substring(j);
				else result = result.Substring(0, i);
				i = result.ToLower().IndexOf("&" + ParameterName.ToLower() + "=");
				if (i > 0) j = result.ToLower().IndexOf("&", i + 1);
			}
			string[] ParameterValues = ParameterValue.Split(',');
			if (ParameterValues.Length > 0) 
			{
				for (i = 0; i<ParameterValues.Length; i++)
					result = result + (result.IndexOf('?')!=-1?'&':'?') + ParameterName + "=" + System.Web.HttpUtility.UrlEncode(ParameterValues[i]);
			} 
			else result = result + (result.IndexOf('?')!=-1?'&':'?') + ParameterName + "=" + System.Web.HttpUtility.UrlEncode(ParameterValue);
			result = result.Replace("&&", "&");
			if (result.Substring(0, 1) == "&") result = result.Substring(2);
			return result;
		}

		//---------------------------------------
		//Retrieves a value of the GET input parameter.
		//---------------------------------------
		public static string CCGetFromGet(string key, string defaultValue)
		{
	        System.Web.HttpRequest Request = System.Web.HttpContext.Current.Request;
			return Request.QueryString[key] == null ? defaultValue : Request.QueryString[key];
		}

		//---------------------------------------
		//Retrieves a value of the POST input parameter.
		//---------------------------------------
		public static string CCGetFromPost(string key, string defaultValue)
		{
	        System.Web.HttpRequest Request = System.Web.HttpContext.Current.Request;
			return Request.Form[key] == null ? defaultValue : Request.Form[key];
		}

		//---------------------------------------
		//Formats a date value according to the specified format mask.
		//---------------------------------------
		public static string CCFormatDate(object dateString, string format)
		{
			return CCFormatDate(CCParseDate(dateString,""),format);
		}

		//---------------------------------------
		//Formats a date value according to the specified format mask.
		//---------------------------------------
		public static string CCFormatDate(DateTime date, string format)
		{
			DateField df = new DateField(format);
			df.Value = date;
			return df.GetFormattedValue();
		}

		//---------------------------------------
		//Parses the specified date string into a date value according to the specified date format. 
		//---------------------------------------
		public static DateTime CCParseDate(object dateString, string format)
		{
			if (dateString is string && (string)dateString == "") return DateTime.MinValue;
			DateField df = new DateField(format);
			df.SetValue(dateString);
			return (DateTime)df.Value;
		}

		//---------------------------------------
		//Gets a value indicating whether the match is successful.
		//---------------------------------------
		public static bool CCRegExpTest(string TestValue, string RegExpMask, bool IgnoreCase, bool GlobalTest)
		{
			int iIgnoreCase = IgnoreCase?(int)RegexOptions.IgnoreCase:0;
			int iGlobalTest = GlobalTest?(int)RegexOptions.Multiline:0;
            Regex mask = new Regex(@TestValue, (RegexOptions)(iIgnoreCase|iGlobalTest) );
            return mask.Match(TestValue).Success;
		}

		//---------------------------------------
		//Looks up a value from the database by executing a database query against a connection.
		//---------------------------------------
		public static object CCDLookUp(string ColumnName, string TableName, string Where, DataAccessObject Connection)
		{
			string SQL = "SELECT "+ColumnName+" FROM "+TableName;
			if (Where.Length > 0) SQL = SQL + " WHERE " + Where;
			return Connection.ExecuteScalar(SQL);
		}

		//---------------------------------------
		//Global variable
		//---------------------------------------
		private	static Hashtable _calendar_config;
		private	static Hashtable _calendar_permissions;
        private static string _calendar_languages;
 
		public static void calendar_configResetCache()
		{
			_calendar_config = null;
		}

		public static Hashtable calendar_config
		{
			get	
			{
				if (_calendar_config==null)	 getGlobalVariable();
				return _calendar_config;
			}
		}
 
		public static Hashtable calendar_permissions
		{
			get	
			{
				if (_calendar_permissions==null)  getGlobalVariable();
				return _calendar_permissions;
			}
		}

        public static string calendar_languages
        {
            get
            {
                if (_calendar_languages == null) getGlobalVariable();
                return _calendar_languages;
            }
        }

		public static int int_calendar_config (string key)
		{
			object val = calendar_config[key];
			if (val == null || val.Equals(DBNull.Value)) return 0;
			if (val is int) return (int)val;
			return Convert.ToInt32(val.ToString());
		}

		public static string str_calendar_config (string key)
		{
			object val = calendar_config[key];
			if (val == null || val.Equals(DBNull.Value)) return "";
			return val.ToString();
		}

		public static int int_calendar_permissions (string key)
		{
			object val = calendar_permissions[key];
			if (val == null || val.Equals(DBNull.Value)) return 0;
			if (val is int) return (int)val;
			return Convert.ToInt32(val.ToString());
		}
 
		//---------------------------------------
		//Read all global variable
		//---------------------------------------
		public static void getGlobalVariable()
		{
			DataAccessObject Conn =	Settings.calendarDataAccessObject;
			string config_var;
			_calendar_config = new Hashtable();
			_calendar_permissions = new Hashtable();
            _calendar_languages = "";
 
			//Read config for calendar
            // DataRowCollection dr = Conn.RunSql("SELECT config_var, config_value, config_listbox FROM config").Tables[0].Rows;

            //added on 15th june
            DataTable dt = new DataTable();
            dt.Columns.Add("config_var");
            dt.Columns.Add("config_value");
            dt.Columns.Add("config_listbox");

            //DataRow dtrw;
            // dtrw = dt.NewRow();
            // dt.Rows.Add(dtrw);

            DataRowCollection dr = dt.Rows;
            //added on 15th june


            for (int i = 0; i < dr.Count; i++)
            {
                config_var = (string)dr[i]["config_var"];
                calendar_config[config_var] = dr[i]["config_value"];
                if (config_var == "default_language")
                    _calendar_languages = dr[i]["config_listbox"].ToString();
            }
 
			//Read permissions for calendar;
            //DataRowCollection drper = Conn.RunSql("SELECT permission_var, permission_value FROM permissions").Tables[0].Rows;

            DataTable dtpermis = new DataTable();
            dt.Columns.Add("permission_var");
            dt.Columns.Add("permission_value");
            DataRowCollection drper = dtpermis.Rows;
            for (int i = 0; i < drper.Count; i++)
            {
                config_var = drper[i]["permission_var"].ToString();
                calendar_permissions[config_var] = drper[i]["permission_value"];

            }


			switch ((string)calendar_config["time_format"]) {
				case "2": System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern = "HH\\:mm"; break;
				case "3": System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortTimePattern = "hh\\:mm tt"; break;
			}
		}
 
 
		//---------------------------------------
		// Generate	new	password
		// return the string
		//---------------------------------------
		public static string generateNewPassword(int PassLength)
		{
			int	OneHdigit;
			string result = "";
			Random rndm = new Random();
			for	(int i = 0;	i<PassLength; i++) 
			{
				OneHdigit =	Convert.ToInt32(rndm.Next(16));
				result = result	+ OneHdigit.ToString("X");
			}
			return result;
		}
 
		//---------------------------------------
		// Add filtering for group of events
		// return condition	for	WHERE
		//---------------------------------------
		public static string AddGroupsFilter(string Where)
		{
			string category	= (string)System.Web.HttpContext.Current.Session["category"];
			string result;
 
			if (category.Length	> 0) 
			{
				if (Where.Length > 0) 
				{
					result = " AND ";
				} 
				else 
				{
					result = "";
				}
				result = result	+ "(events.category_id = " + category +	") ";
			} 
			else 
			{
				result	= "";
			}
			return result;
		}
 
		//---------------------------------------
		//
		//---------------------------------------
		public static string AddReadFilter(string Where)
		{
			int	user_level;
			string result =	"";
 
			if (DBUtility.UserId !=	null) 
			{
				user_level = Convert.ToInt32(DBUtility.UserGroup); //10	for	registred and 100 for Admin;
			} 
			else 
			{
				user_level = 0;	//not logged-in	user --	Everyone;
			}
 
			if (user_level < int_calendar_permissions("private_read") || (user_level >= int_calendar_permissions("private_read") && int_calendar_permissions("private_read") == 50)) 
			{
				if (Where.Length > 0)  result =	result + " AND ";
				result = result	+ "(events.event_is_public = 1 ";
                if (int_calendar_permissions("private_read") == 50 && DBUtility.UserId != null)
                    result += " OR (events.event_is_public=0 AND events.Sch_ID=" + Convert.ToInt32(DBUtility.UserId) + ")";
				result += ")";
			} 
			else 
			{
				result = "";
			}
			return result;
		}

		//---------------------------------------
		//
		//---------------------------------------
		public static bool	EditAllowed(int	event_id)
		{
			DataAccessObject Conn =	Settings.calendarDataAccessObject;
			string SQL;
			DataRowCollection dr;
			string event_is_public = "";
			int	event_owner	= 0;
			int	user_level;
			int	effective_rights;
			bool result	= false;

            SQL = "SELECT event_is_public, Sch_ID FROM	events WHERE event_id=" + Conn.ToSql(event_id.ToString(), FieldType.Integer);
			dr = Conn.RunSql(SQL).Tables[0].Rows;
			if (dr.Count > 0) 
			{
				event_is_public	= dr[0]["event_is_public"].ToString();
				//event_owner	= Convert.ToInt32(dr[0]["user_id"]);
			}

			if (event_is_public	== "1")	
			{
				effective_rights = int_calendar_permissions("public_update");
			} 
			else 
			{
				effective_rights = int_calendar_permissions("private_update");
			}

			if (DBUtility.UserId !=	null) 
			{
				user_level = Convert.ToInt32(DBUtility.UserGroup); // 10 for registred and 100 for Admin;
				if (event_owner == Convert.ToInt32(DBUtility.UserId) && (user_level < 100 || effective_rights == 50))
				{
					user_level = 50;  //if logged_in user and not admin	but	owner of event;
				}
			} 
			else 
			{
				user_level = 0;	//not logged-in	user --	Everyone;
			}
 
			if (user_level < effective_rights || (event_is_public != "1" && effective_rights == 50 && user_level != 50))
			{
				result = true;
			} 
			else 
			{
				result = true;
			}
			return result;

		}

 
		//---------------------------------------
		//
		//---------------------------------------
		public static bool	AddAllowed()
		{
			int	user_level = 0;
			bool result	= false;
 
			if (DBUtility.UserId !=	null) 
			{
				user_level = Convert.ToInt32(DBUtility.UserGroup); // 10 for registred and 100 for Admin;
			} 
			else 
			{
				user_level = 100;	//not logged-in	user --	Everyone;
			}
 
			if (user_level < int_calendar_permissions("new_event")) 
			{
				result = false;
			} 
			else 
			{
				result = true;
			}
			return result;
		}
 
 
		//---------------------------------------
		//
		//---------------------------------------
		public static bool	DeleteAllowed(int event_id)
		{
			DataAccessObject Conn =	Settings.calendarDataAccessObject;
			string SQL;
			DataRowCollection dr;
			string event_is_public = "";
			int	event_owner	= 0;
			int	user_level;
			int	effective_rights;
			bool result	= false;

            SQL = "SELECT event_is_public, Sch_ID FROM	events WHERE event_id=" + event_id.ToString();
 
			dr = Conn.RunSql(SQL).Tables[0].Rows;
			if (dr.Count > 0) 
			{
				event_is_public	= dr[0]["event_is_public"].ToString();
				//event_owner	= Convert.ToInt32(dr[0]["user_id"]);
			}
			if (event_is_public	== "1")	
			{
				effective_rights = int_calendar_permissions("public_delete");
			} 
			else 
			{
				effective_rights = int_calendar_permissions("private_delete");
			}
 
			if (DBUtility.UserId !=	null) 
			{
				user_level = Convert.ToInt32(DBUtility.UserGroup); // 10 for registred and 100 for Admin;
				if (event_owner	== Convert.ToInt32(DBUtility.UserId) && (user_level < 100 || effective_rights == 50)) 
				{
					user_level = 50;  // if	logged_in user and not admin but owner of event;
				}
			} 
			else 
			{
				user_level = 0;	//not logged-in	user --	Everyone;
			}
 
			if (user_level < effective_rights || (event_is_public != "1" && effective_rights == 50 && user_level != 50))
			{
				result = false;
			} 
			else 
			{
				result = true;
			}
			return result;
		}
  
		//---------------------------------------
		//
		//---------------------------------------
		public static bool	ReadAllowed(int	event_id)
		{
			DataAccessObject Conn =	Settings.calendarDataAccessObject;
			string SQL = "";
			DataRowCollection dr;
			string event_is_public = "";
			int	event_owner	= 0;
			int	user_level = 0;
			bool result	= false;

            SQL = "SELECT event_is_public, Sch_ID FROM	events WHERE event_id=" + Conn.ToSql(event_id.ToString(), FieldType.Integer);
 
			dr = Conn.RunSql(SQL).Tables[0].Rows;
			if (dr.Count > 0) 
			{
				event_is_public	= dr[0]["event_is_public"].ToString();
				//event_owner	= Convert.ToInt32(dr[0]["user_id"]);
			}
 
			if (event_is_public	== "1")	
			{
				result = true;
			} 
			else 
			{
				if (DBUtility.UserId !=	null) 
				{
					user_level = Convert.ToInt32(DBUtility.UserGroup);	// 10 for registred	and	100	for	Admin;
					if (event_owner == Convert.ToInt32(DBUtility.UserId) && (user_level < 100 || int_calendar_permissions("private_read") == 50))
					{
						user_level = 50;  // if	logged_in user and not admin but owner of event;
					}
				} 
				else 
				{
					user_level = 0;	//not logged-in	user --	Everyone;
				}
 
				if (user_level < int_calendar_permissions("private_read") || (int_calendar_permissions("private_read") == 50 && user_level != 50))
				{
					result = false;
				} 
				else 
				{
					result = true;
				}
			}
			return result; 
		}
 

		//---------------------------------------
		//
		//---------------------------------------
		public static void	processCustomFields(Control	sender, string prefix)
		{
			DataAccessObject Conn =	Settings.calendarDataAccessObject;
			string SQL;
			DataRowCollection dr;
			string label_name;
 
			SQL	= "SELECT field_name, "	+
				"custom_fields.field_label AS mainLabel, " +
				"custom_fields_langs.field_label AS	localeLabel, " +
				"field_is_active " +
				"FROM custom_fields_langs INNER	JOIN custom_fields " +
				"ON	custom_fields.field_id = custom_fields_langs.field_id "	+
				"WHERE language_id = " + Conn.ToSql((string)System.Web.HttpContext.Current.Session["locale"], FieldType.Text);
 
			dr = Conn.RunSql(SQL).Tables[0].Rows;
			for	(int i = 0;	i<dr.Count;	i++) 
			{
				if (dr[i]["field_is_active"].ToString() == "1") 
				{
					if (((string)dr[i]["localeLabel"]).Length >	0) 
					{
						label_name = (string)dr[i]["localeLabel"];
					} 
					else 
					{
						label_name = (string)dr[i]["mainLabel"];
					}

					System.Web.UI.WebControls.Literal labelCtrl = (System.Web.UI.WebControls.Literal)sender.FindControl(prefix + "Label" + (string)dr[i]["field_name"]);
					if (labelCtrl != null) labelCtrl.Text = label_name;
				} 
				else 
				{
					Control	panelCtrl = sender.FindControl(prefix +	"Panel"	+ (string)dr[i]["field_name"]);
					if (panelCtrl != null) panelCtrl.Visible = false;
				}
			}
 
		}
 
		private static string GetDBStringHelper(object value)
		{
			if (value==null || value==DBNull.Value) return null;
			else return value.ToString();
		}

		//---------------------------------------
		//
		//---------------------------------------
		public static void SendEmailMessage(string variable, string	email_to, Hashtable	parameters)
		{
 			if (variable.Length	> 0) 
			{
				string email_Subject;
				string email_body;
				string email_from;

				DataAccessObject Conn =	Settings.calendarDataAccessObject;
				string SQL	= "SELECT email_template_from, " +
					"email_templates.email_template_Subject	AS mainSubject,	" +
					"email_templates_lang.email_template_Subject AS	localeSubject, " +
					"email_templates.email_template_body AS	mainBody, "	+
					"email_templates_lang.email_template_body AS localeBody	" +
					"FROM email_templates LEFT JOIN	email_templates_lang " +
					"ON	email_templates.email_template_id =	email_templates_lang.email_template_id " +
					"WHERE email_template_type = " + Conn.ToSql(variable, FieldType.Text) +
					" AND language_id =	" +	Conn.ToSql((string)System.Web.HttpContext.Current.Session["locale"], FieldType.Text);
 
				DataRowCollection dr = Conn.RunSql(SQL).Tables[0].Rows;
				if (dr.Count > 0) 
				{
					if (GetDBStringHelper(dr[0]["localeSubject"])!=null && 
						((string)dr[0]["localeSubject"]).Length	> 0) 
					{
						email_Subject =	(string)dr[0]["localeSubject"];
					} 
					else 
					{
						email_Subject = GetDBStringHelper(dr[0]["mainSubject"])!=null?(string)dr[0]["mainSubject"]:"";
					}
 
					if (GetDBStringHelper(dr[0]["localeBody"])!=null && 
						((string)dr[0]["localeBody"]).Length > 0) 
					{
						email_body = (string)dr[0]["localeBody"];
					} 
					else 
					{
						email_body = GetDBStringHelper(dr[0]["mainBody"])!=null?(string)dr[0]["mainBody"]:"";
					}
 
					if (GetDBStringHelper(dr[0]["email_template_from"])!=null && 
						((string)dr[0]["email_template_from"]).Length > 0) 
					{
						email_from = (string)dr[0]["email_template_from"];
					} 
					else 
					{
						email_from = GetDBStringHelper(str_calendar_config("site_email"));
					}

					if (email_body ==null) email_body = " ";

					foreach (string key in parameters.Keys)
					{
						email_body = email_body.Replace(key, (string)parameters[key]);
					}
					email_body = email_body.Replace("{site_url}", Settings.ServerURL);
 
					if (email_from == null || email_from == "") email_from = "somebody@somedomain";
					System.Web.Mail.MailMessage	message	= new System.Web.Mail.MailMessage();
					message.From = email_from;
					message.To = email_to;
					message.Subject	= email_Subject;
					message.Body = email_body;
					message.BodyFormat = 0;
					System.Web.Mail.SmtpMail.Send(message);
				}
			}
		}
 
		//---------------------------------------
		// Read	Content
		//---------------------------------------
		public static string GetContent(string	strkey)
		{
			DataAccessObject Conn =	Settings.calendarDataAccessObject;
			DataRowCollection dr;
			string SQL;
			string result =	"";
 
			SQL	= "SELECT contents.content_value as	mainValue, contents_langs.content_value	as localeValue " +
				"FROM contents LEFT	JOIN contents_langs	ON contents.content_id = contents_langs.content_id " +
				"WHERE language_id=" + Conn.ToSql((string)System.Web.HttpContext.Current.Session["locale"],	FieldType.Text)	+
				" AND content_type=" + Conn.ToSql(strkey, FieldType.Text);
 
			dr = Conn.RunSql(SQL).Tables[0].Rows;
			if (dr.Count !=	0) 
			{
				result = (string)dr[0]["localeValue"];
				if (result==null ||	result.Trim().Length ==	0) 
				{
					result = (string)dr[0]["mainValue"];
				}
			}
			return result;
		}
 
	}
}
